<template>
  <view class="TeamForm">
    <view class="remind">注意：每人最多可创建5支队伍</view>
    <view class="item">
      <text>队名</text>
      <view class="inputBox">
        <input
          type="text"
          placeholder="请输入队名"
          v-model="teamDetail.title"
        />
      </view>
    </view>
    <view class="item">
      <text>介绍</text>
      <view class="inputBox">
        <input
          type="text"
          placeholder="请输入介绍"
          v-model="teamDetail.introduce"
        />
      </view>
    </view>
    <view class="item">
      <text>标签</text>
      <view class="themeBox inputBox" @click="showTagBox = true">
        <view class="inputTag">
          <text v-if="!teamDetail.tags.length" style="color: #898989"
            >请选择标签</text
          >
          <view class="tagsGroup" v-else>
            <view
              class="chooseTag"
              v-for="(item, index) in teamDetail.tags"
              :key="index"
              >{{ item }}</view
            >
          </view>
        </view>
      </view>
    </view>
    <view class="item">
      <text>密码(默认为公开)</text>
      <view class="inputBox">
        <input
          type="password"
          placeholder="设置密码"
          v-model="teamDetail.password"
        />
      </view>
    </view>
    <view class="item">
      <text>限制人数</text>
      <van-stepper
        :value="teamDetail.number"
        @change="handleNumberChange"
        min="2"
        max="6"
        class="stepper"
      />
    </view>

    <view class="item">
      <text>封面(默认为个人头像)</text>
      <van-uploader
        :file-list="fileList"
        @after-read="handleChoosePic"
        :max-size="2100000"
        :max-count="1"
        class="uploadPic"
      />
    </view>

    <view class="btnItem">
      <van-button block class="myBtn" color="#aaa" @click="handleCloseForm"
        >取消</van-button
      >
      <van-button
        block
        class="myBtn"
        color="#05A47D"
        :disabled="btnLoading"
        @click="handleSubmitDiscussion"
        >创建队伍</van-button
      >
    </view>

    <!-- 选择标签组件 -->
    <view :class="['mask', showTagBox ? 'maskActive' : '']" v-if="showTagBox">
      <view class="chooseTagBox">
        <view class="tagBox animate__animated animate__bounceIn">
          <view class="tagTitle">选择标签</view>
          <SelectTagBox
            @chooseTagFinished="handleFinishTag"
            :tagList="tagList"
            :maxNumber="maxTagNumber"
          />
          <view class="btnGroup">
            <van-button
              block
              size="small"
              color="#aaa"
              @click="showTagBox = false"
              >取消</van-button
            >
            <van-button
              block
              size="small"
              color="#05A47D"
              @click="handleConfirmTag"
              >选择完成</van-button
            >
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from "vuex";
import SelectTagBox from "../public/SelectTagBox.vue";
export default {
  name: "TeamForm",
  components: {
    SelectTagBox,
  },
  data() {
    return {
      teamDetail: {
        title: "",
        introduce: "",
        password: "",
        number: 2,
        tags: [],
      },
      showTagBox: false,
      btnLoading: false,
      maxTagNumber: 3,
      fileList: [],
      chooseTags: [],
      tagList: [
        "前端",
        "后端",
        "游戏",
        "竞赛",
        "Java",
        "Vue",
        "JavaScript",
        "React",
      ],
    };
  },
  computed: { ...mapState(["userInfo"]) },
  methods: {
    // 关闭表单
    handleCloseForm() {
      this.teamDetail = {
        title: "",
        introduce: "",
        password: "",
        number: 2,
        tags: [],
      };
      this.fileList = [];
      this.$emit("closeForm");
    },

    // 提交表单
    async handleSubmitDiscussion() {
      this.btnLoading = true;
      if (this.validData()) {
        const composeTeam = this.composeTeamData(),
          teamTaskContent = this.composeTeamTaskData(),
          userId = this.userInfo._openid;
        // 说明不上传封面：选择用户头像做封面
        uni.showLoading({
          title: "创建中",
          mask: true,
        });
        try {
          if (!this.fileList.length) {
            composeTeam.cover = this.userInfo.avatar;
            this.$store.commit("m_team/setTeamDetail", composeTeam);
          } else {
            this.$store.commit("m_team/setTeamDetail", composeTeam);
            await this.$store.dispatch("m_team/uploadTeamCover", this.fileList);
          }

          const teamId = await this.$store.dispatch("m_team/uploadTeamDetail");
          await this.$store.dispatch("m_task/addTeamTaskList", {
            userId,
            teamTaskContent,
            teamId,
          });
          this.getTeamListData();
          uni.hideLoading();
          uni.showToast({
            icon: "success",
            title: "创建成功",
            duration: 1000,
          });
        } catch (err) {
          uni.showToast({
            icon: "error",
            title: "创建失败",
            duration: 1000,
          });
          console.log(err);
        }
        this.teamDetail = {
          title: "",
          introduce: "",
          password: "",
          number: 2,
          tags: [],
        };
        this.fileList = [];
        this.$emit("closeForm");
      }
      this.btnLoading = false;
    },

    // 处理选择队伍封面
    handleChoosePic(event) {
      const { file } = event.detail;
      const item = {};
      console.log(file);
      item.url = file.url;
      item.name =
        Math.floor(new Date().getTime() / 1000) +
        "-" +
        this.userInfo.nickName +
        "-team";
      item.deletable = true;
      item.file = file;
      this.fileList.push(item);
    },

    // 创建成功后重新获取队伍列表
    async getTeamListData(page = 0, limitCount = 10) {
      this.$store.commit("m_team/clearTeamList");
      await this.$store.dispatch("m_team/getTeamList", { page, limitCount });
    },

    // 扩充队伍记录字段
    composeTeamData() {
      const team = this.teamDetail;
      team.userList = [];
      team.refuseList = []; // 拒绝列表
      team.author = {};
      team.createTime = new Date();
      team.author.avatar = this.userInfo.avatar;
      team.author.nickName = this.userInfo.nickName;
      return team;
    },

    // 整合队伍任务列表
    composeTeamTaskData() {
      const item = {};
      item.isMe = false;
      item.isTeam = true;
      item.tasks = [];
      item.title = this.teamDetail.title;
      item.createTime = new Date();
      return item;
    },

    // 确认按钮逻辑（验证拿到的标签数量）
    handleConfirmTag() {
      if (this.chooseTags.length !== 3) {
        uni.showToast({
          title: "不少于3个标签",
          icon: "error",
          duration: 1000,
        });
        return;
      } else {
        uni.showToast({
          title: "已保存",
          icon: "success",
          duration: 1000,
        });
        this.showTagBox = false;
        this.teamDetail.tags = this.chooseTags;
      }
    },

    // 保存Select中拿到的标签
    handleFinishTag(tags) {
      this.chooseTags = tags;
    },

    // 步进器变化
    handleNumberChange(e) {
      this.teamDetail.number = e.detail;
    },

    // 验证输入的表单
    validData() {
      if (!this.userInfo.avatar.length || !this.userInfo.nickName.length) {
        uni.showToast({
          icon: "error",
          title: "请先进行登录",
          duration: 1000,
        });
        return false;
      }
      if (this.userInfo.myTeam.length >= 5) {
        uni.showToast({
          icon: "error",
          title: "已有队伍过多",
          duration: 1000,
        });
        return false;
      }
      if (!this.teamDetail.title.trim().length) {
        uni.showToast({
          icon: "error",
          title: "请填写队名",
          duration: 1000,
        });
        return false;
      }
      if (this.teamDetail.title.trim().length > 10) {
        uni.showToast({
          icon: "error",
          title: "队名过长",
          duration: 1000,
        });
        return false;
      }
      if (!this.teamDetail.introduce.trim().length) {
        uni.showToast({
          icon: "error",
          title: "请填写介绍",
          duration: 1000,
        });
        return false;
      }
      if (!this.teamDetail.introduce.trim().length > 30) {
        uni.showToast({
          icon: "error",
          title: "介绍过长",
          duration: 1000,
        });
        return false;
      }
      if (!this.teamDetail.tags.length) {
        uni.showToast({
          icon: "error",
          title: "请设置标签",
          duration: 1000,
        });
        return false;
      }
      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
.TeamForm {
  width: 100%;
  height: 100%;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  .item {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    font-size: 28rpx;
    color: #aaa;
    margin-bottom: 30rpx;
  }
  .specialItem {
    width: 100%;
    display: flex;
    justify-content: space-around;
  }
  .inputBox {
    padding: 10rpx 20rpx;
    width: 85%;
    background-color: #eee;
    border-radius: 20rpx;
    margin-top: 20rpx;
  }
  .stepper,
  .uploadPic {
    margin-top: 20rpx;
  }

  .btnItem {
    width: 100%;
    display: flex;
    justify-content: space-around;
    .myBtn {
      width: 200rpx;
      margin-right: 50rpx;
    }
  }
  .mask {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: -10000;
  }
  .maskActive {
    z-index: 100000;
  }
  .tagsGroup {
    display: flex;
    .chooseTag {
      display: flex;
      align-items: center;
      padding: 4rpx 10rpx;
      margin: 0 10rpx;
      border-radius: 5rpx;
      background-color: #f4f4f5;
      color: #909399;
      border: 1px solid #e9e9eb;
      font-size: 26rpx;
    }
  }
  .chooseTagBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    .tagBox {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 400rpx;
      padding: 20rpx;
      background-color: #fff;
      z-index: 100;
      border-radius: 10rpx;
      box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.3);
      .btnGroup {
        width: 300rpx;
        margin-top: 40rpx;
        display: flex;
        justify-content: space-between;
      }
      .tagTitle {
        font-size: 38rpx;
        margin-bottom: 30rpx;
      }
      .tagContent {
        width: 300rpx;
        height: 100%;
      }
    }
  }
  .remind {
    width: 100%;
    font-size: 26rpx;
    color: #aaa;
    margin-bottom: 10rpx;
  }
}
</style>
